import React, { Component } from 'react'
import chat from './chat.module.css'
class Chat extends Component {
    constructor(props) {
        super(props)
        this.state = {
            ws: null,
            count: 0,
            userId: null, //当前用户ID
            list: [], //聊天记录的数组
            contentText: "", //input输入的值
        }
    }
    componentDidMount() {
        this.getUserID();
        this.initWebSocket()
        console.log(this.msgBox.current)
    }
    //根据时间戳作为当前用户ID
    getUserID = () => {
        let time = new Date().getTime();
        this.setState({
            userId: time
        })
    }
    //根据userID生成一个随机头像
    getUserHead = (id, type) => {
        let ID = String(id);
        if (type == "bck") {
            return Number(ID.substring(ID.length - 3));
        }
        if (type == "polygon") {
            return Number(ID.substring(ID.length - 2));
        }
        if (type == "rotate") {
            return Number(ID.substring(ID.length - 3));
        }
    }
    //滚动条到底部
    scrollBottm = () => {
        let el = this.msgBox;
        el.scrollTop = el.scrollHeight;
    }
    //发送聊天信息
    sendText = () => {
        let _this = this;
        // _this.sendMsg.focus();
        if (!_this.state.contentText) {
            return;
        }
        let params = {
            userId: _this.state.userId,
            msg: _this.state.contentText
        };
        _this.state.ws.send(JSON.stringify(params)); //调用WebSocket send()发送信息的方法
        _this.setState({
            contentText: ''
        })
        // _this.state.contentText = "";
        setTimeout(() => {
            _this.scrollBottm();
        }, 500);
    }
    //进入页面创建websocket连接
    initWebSocket = () => {
        let _this = this;
        //判断页面有没有存在websocket连接
        if (window.WebSocket) {
            let ws = new WebSocket("ws://localhost:8181");
            _this.setState({
                ws: ws
            })
            // _this.ws = ws;
            //创建服务器完毕后的回调函数
            ws.onopen = function (e) {
                console.log("服务器连接成功");
            };
            //服务器关闭的回调函数
            ws.onclose = function (e) {
                console.log("服务器连接关闭");
            };
            //连接错误时的回调函数
            ws.onerror = function () {
                console.log("服务器连接出错");
            };
            //接收返回数据时的回调函数
            ws.onmessage = function (e) {
                //接收服务器返回的数据
                let resData = JSON.parse(e.data);
                if (resData.funName == "userCount") {
                    _this.setState({
                        count: resData.users,
                        list: [...resData.chat]
                    })
                } else {
                    _this.setState({
                        list: [..._this.state.list,
                        { userId: resData.userId, content: resData.msg }]
                    })
                }
            };
        }
    }
    changeValue = (e) => {
        this.setState({
            contentText: e.target.value
        })
    }
    render() {
        const {name} = this.props.history.location.state
        return (<div className={chat.chat}>
            <div className={chat.header}>
                <span onClick={() => this.props.history.go(-1)}>&lt;</span>
                <span style={{flex: 1, textAlign: 'center'}}>{name?name:''}</span>
            </div>
            <div className={chat.main}>
                <div className={chat.msgBox} ref={(msgBox) => this.msgBox = msgBox}>
                    {
                        this.state.list.map((i, index) => <div key={index} className={chat.msg} style={{flexDirection: i.userId == this.state.userId? 'row-reverse':''}}>
                            <div className={chat.userHead}>
                                <div className={chat.head} style={{background: `hsl(${this.getUserHead(i.userId,'bck')}, 88%, 62%)`,clipPath: `polygon(${this.getUserHead(i.userId,'polygon')}% 0,100% 100%,0% 100%)`, transform: `rotate(${this.getUserHead(i.userId,'rotate')}deg)`}}></div>
                            </div>
                            <div className={chat.userMsg}>
                                <span style={{float: i.userId == this.state.userId ?'right': ''}} className={i.userId == this.state.userId ? chat.right : chat.left}>{i.content}</span>
                            </div>
                        </div>)
                    }
                </div>
            </div>
            <div className={chat.footer}>
                <div className={chat.inputBox}>
                    <input type={chat.text} ref={(sendMsg) => this.sendMsg = sendMsg} value={this.state.contentText} onChange={this.changeValue} />
                    <div className={this.state.contentText ? chat.active : chat.btn} onClick={this.sendText}>发送</div>
                </div>
            </div>
        </div>
        )
    }
}

export default Chat